<template>
  <div class="edit-title">
    <span>我的头像</span>
  </div>
  <div class="profilePhoto">
    <div class="profilePhotoDiv">
      <div class="changeProfilePhoto">
        <el-upload
          action="#"
          :file-list="fileList"
          :limit="1"
          :multiple="true"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadProfilePhoto">
          <span>更换头像</span>
        </el-upload>
      </div>
      <div class="profilePhotoBox">
        <div class="avatar-uploader">
          <img v-if="profilePhotoUrl" :src="profilePhotoUrl" class="profilePhotoImg">
          <i v-else class="default-profilePhotoImg" />
        </div>
      </div>
      <div class="changePendant">
        <el-form>
          <el-upload action="#" :show-file-list="false" :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload" :http-request="changePendant" >
            <span>更换挂件</span>
          </el-upload>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { uploadAttachment } from '@/services/util/util'
import { downloadUrl, regexImage } from '@/script/util'

import storage from '@/utils/common/storage'

import { saveUserInfo } from '@/services/index/personalCentre/personalCenter'

export default {
  name: 'ProfilePhoto',
  emits: ['uploaded', 'aboutToUpload', 'removed'],
  data () {
    return {
      fileList: [],
      profilePhotoUrl: storage.get('user') ? JSON.parse(storage.get('user')).image : ''
    }
  },
  inject: ['reload'],
  methods: {
    beforeAvatarUpload () {
      if (this.fileList.length <= 0) {
        return false
      }
      if (this.fileList.length > 1) {
        this.$message.error('您不能上传超过一个文件')
        return false
      }
      const file = this.fileList[0]
      if (!regexImage.test(file.raw.type)) {
        this.$message.error('暂不支持此类文件')
        return false
      }
    },
    handleAvatarSuccess (res, file) {
      this.profilePhotoUrl = URL.createObjectURL(file.raw)
    },
    async uploadProfilePhoto () {
      const formData = new FormData()
      this.fileList.forEach((val, index) => {
        formData.append('files', val.raw)
      })
      formData.append('scope', 'profilePhotoFile')
      formData.append('isSecure', 'NO')
      const config = {
        timeout: 120000, // 设置超时时长
        onUploadProgress: function (progress) {
          this.fileList.percent = Math.round(
            (progress.loaded * 80) / progress.total
          )
        }.bind(this)
      }
      uploadAttachment(formData, config).then((res) => {
        if (res.code !== 10000) {
          this.$message.error('图片上传失败')
          return
        }
        this.profilePhotoUrl = downloadUrl + res.data[0].attachNo
        // 再次调用更新用户数据
        const userInfo = {
          userBaseInfo: {
            image: res.data[0].attachNo
          },
          strategy: 'Profile Photo'
        }
        const attachNo = res.data[0].attachNo
        let execFlag = false
        saveUserInfo(userInfo).then((execRes) => {
          if (execRes.code !== 10000) {
            execFlag = true
          }
          // 如果更新用户数据失败则回滚
          if (execFlag) { return }
          // 更新缓存
          const user = this.$store.state.user
          user.image = attachNo
          this.$store.dispatch('saveUserInfo', user)
          this.$message.success('上传成功')
          this.reload()
        })
      })
    },
    changePendant () {

    }
  }
}
</script>

<style scoped lang="less">
@import "profilePhoto";
</style>
